define(['jquery', 'bootstrap', 'backend', 'table', 'form','litestoregoods'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'integralgoods/index' + location.search,
                    // add_url: 'integralgoods/add',
                    // edit_url: 'integralgoods/edit',
                    // del_url: 'integralgoods/del',
                    multi_url: 'integralgoods/multi',
                    import_url: 'integralgoods/import',
                    dragsort_url: '',
                    table: 'goods',
                }
            });

            var table = $("#table");
            $(".btn-add").data("area", ["100%", "100%"]);
            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["100%", "100%"]);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'goods_id',
                sortName: 'weigh',
                searchFormTemplate: 'customformtpl',
                searchFormVisible: true,
                search:false,
                showColumns:false,
                showExport:false,
                // commonSearch:false,
                pageSize: 10,
                showToggle: false,
                maintainSelected: true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'goods_id', title: __('Goods_id')},
                        {field: 'images', title: __('Images'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.images},
                        {field: 'goods_name', title: __('Goods_name'), operate: 'LIKE'},
                        {field: 'manystoreshop.name', title: '所屬商家', operate: false},
                        {field: 'goodscategory.name', title: '積分商品分類', operate: 'LIKE'},
                        {field: 'integral', title: '售價'},
                        {field: 'sales_actual', title: '已兌'},
                        {field: 'stock_num', title: '庫存'},
                        {field: 'goods_status_text', title: __('Goods_status')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter:function(value,row,index){
                                    this.buttons = [{
                                            name: 'refuse',
                                            text: '上架',
                                            classname: 'btn btn-xs btn-warning btn-magic btn-ajax',
                                            url: 'integralgoods/updategoods',
                                            confirm: '是否確認上架？',
                                            visible: function (row) {
                                                if ( Config.updategoods && row.goods_status == '20' ) {
                                                    return true;
                                                }else{
                                                    return false;
                                                }
                                                //返回true时按钮显示,返回false隐藏
                                            },
                                            success: function () {
                                                $(".btn-refresh").trigger("click");
                                            },
                                            error: function () {

                                            },
                                            refresh: true,
                                        },{
                                            name: 'agree',
                                            text: '下架',
                                            classname: 'btn btn-xs btn-danger btn-ajax',
                                            url: 'integralgoods/updategoods',
                                            confirm: '是否確認下架？',
                                            visible: function (row) {
                                                if ( Config.updategoods && row.goods_status == '10' ) {
                                                    return true;
                                                }else{
                                                    return false;
                                                }
                                                //返回true时按钮显示,返回false隐藏
                                            },
                                            success: function () {
                                                $(".btn-refresh").trigger("click");
                                            },
                                            error: function () {

                                            },
                                            refresh: true,
                                        }
                                    ];
                                return Table.api.formatter.operate.call(this,value,row,index);
                            }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            // 批量上下架
            $(document).on("click", ".btn-selected", function () {
                var ids = Table.api.selectedids(table).join(",");
                Layer.confirm("是否批量下架？", {type: 5,title:'操作確認', skin: 'layui-layer-dialog layui-layer-fast'}, function (index) {
                    Fast.api.ajax({
                     url:$('.btn-selected').attr('data-url'),
                     data:{ids:ids,action:'select'},
                    loading:false,
                    }, function (data) {
                        Layer.closeAll();
                        $(".btn-refresh").trigger("click");
                        // $(".btn-compress").trigger("click");
                    })
                })
            });
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'integralgoods/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'integralgoods/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'integralgoods/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Form.api.bindevent($("form[role=form]"), function(data, ret){
                Fast.api.close(data);
                Toastr.success("商品提交成功");
            }, function(data, ret){
                Toastr.success("商品提交失败");
            }, function(success, error){
                //注意如果我们需要阻止表单，可以在此使用return false;即可
                //如果我们处理完成需要再次提交表单则可以使用submit提交,如下
                console.log(this);
                var form = this;
                if (form.size() === 0) {
                    Toastr.error("表单未初始化完成,无法提交");
                    return false;
                }
                var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                url = form.attr("action");
                url = url ? url : location.href;
                //修复当存在多选项元素时提交的BUG
                var params = {};
                var multipleList = $("[name$='[]']", form);
                if (multipleList.size() > 0) {
                    var postFields = form.serializeArray().map(function (obj) {
                        return $(obj).prop("name");
                    });
                    $.each(multipleList, function (i, j) {
                        if (postFields.indexOf($(this).prop("name")) < 0) {
                            params[$(this).prop("name")] = '';
                        }
                    });
                }
                var dataParam = {spec_many: specMany.getData()};
                Fast.api.ajax({
                    type: type,
                    url: url,
                    data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : '') + (Object.keys(dataParam).length > 0 ? '&' + $.param(dataParam) : ''),
                    dataType: 'json',
                    complete: function (xhr) {
                        var return_data = xhr.responseJSON;
                        if ( return_data['code'] == '0' ) {
                        }else{
                            var token = xhr.getResponseHeader('__token__');
                            if (token) {
                                $("input[name='__token__']", form).val(token);
                            }
                            setTimeout(function () {
                                //关闭弹窗
                                var index = parent.Layer.getFrameIndex(window.name);
                                var callback = parent.$("#layui-layer" + index).data("callback");
                                parent.Layer.close(index);
                                //刷新列表
                                parent.$("#table").bootstrapTable('refresh');
                            }, 1000);
                        }
                    }
                }, function (data, ret) {
                    $('.form-group', form).removeClass('has-feedback has-success has-error');
                    if (data && typeof data === 'object') {
                        if (typeof data.token !== 'undefined') {
                            $("input[name='__token__']", form).val(data.token);
                        }
                        if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
                            data.callback.call(form, data);
                        }
                    }
                }, function (data, ret) {
                    if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
                        $("input[name='__token__']", form).val(data.token);
                    }
                });
                return false;
            });

            // 注册商品多规格组件
            var specMany = new GoodsSpec({
                container: '.goods-spec-many',
                OutForm:Form
            });

            // 切换单/多规格
            $('select[name="row[spec_type]"]').change(function (e) {
                var $goodsSpecMany = $('.goods-spec-many')
                    , $goodsSpecSingle = $('.goods-spec-single');

                if (e.currentTarget.value === '10') {

                    $goodsSpecMany.hide() && $goodsSpecSingle.show();
                    $('.goods-spec-many .pay_type_html').html();


                } else {

                    $goodsSpecMany.show() && $goodsSpecSingle.hide();
                    $('.goods-spec-single .pay_type_html').html();
                }
            });
            // Controller.api.bindevent();
        },
        edit: function () {
            // Controller.api.bindevent();
            Form.api.bindevent($("form[role=form]"), function(data, ret){
                //Fast.api.close(data);
                Toastr.success("商品提交成功");
            }, function(data, ret){
                Toastr.success("商品提交失败");
            }, function(success, error){
                //注意如果我们需要阻止表单，可以在此使用return false;即可
                //如果我们处理完成需要再次提交表单则可以使用submit提交,如下
                console.log(this);
                var form = this;
                if (form.size() === 0) {
                    Toastr.error("表单未初始化完成,无法提交");
                    return false;
                }
                var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                url = form.attr("action");
                url = url ? url : location.href;
                //修复当存在多选项元素时提交的BUG
                var params = {};
                var multipleList = $("[name$='[]']", form);
                if (multipleList.size() > 0) {
                    var postFields = form.serializeArray().map(function (obj) {
                        return $(obj).prop("name");
                    });
                    $.each(multipleList, function (i, j) {
                        if (postFields.indexOf($(this).prop("name")) < 0) {
                            params[$(this).prop("name")] = '';
                        }
                    });
                }
                var dataParam = {spec_many: specMany.getData()};
                console.log(dataParam);
                Fast.api.ajax({
                    type: type,
                    url: url,
                    data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : '') + (Object.keys(dataParam).length > 0 ? '&' + $.param(dataParam) : ''),
                    dataType: 'json',
                    complete: function (xhr) {
                        var return_data = xhr.responseJSON;
                        if ( return_data['code'] == '0' ) {
                        }else{
                            var token = xhr.getResponseHeader('__token__');
                            if (token) {
                                $("input[name='__token__']", form).val(token);
                            }
                            setTimeout(function () {
                                //关闭弹窗
                                var index = parent.Layer.getFrameIndex(window.name);
                                var callback = parent.$("#layui-layer" + index).data("callback");
                                parent.Layer.close(index);
                                //刷新列表
                                parent.$("#table").bootstrapTable('refresh');
                            }, 1000);
                        }
                    }
                }, function (data, ret) {
                    $('.form-group', form).removeClass('has-feedback has-success has-error');
                    if (data && typeof data === 'object') {
                        if (typeof data.token !== 'undefined') {
                            $("input[name='__token__']", form).val(data.token);
                        }
                        if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
                            data.callback.call(form, data);
                        }
                    }
                }, function (data, ret) {
                    if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
                        $("input[name='__token__']", form).val(data.token);
                    }
                });
                return false;
            });
            // 注册商品多规格组件
            var specMany = new GoodsSpec({
                container: '.goods-spec-many',
                OutForm:Form
            }, from_specData);


            // 切换单/多规格
            $('select[name="row[spec_type]"]').change(function (e) {
                var $goodsSpecMany = $('.goods-spec-many')
                    , $goodsSpecSingle = $('.goods-spec-single');
                if (e.currentTarget.value === '10') {

                    $goodsSpecMany.hide() && $goodsSpecSingle.show();
                    $('.goods-spec-many .pay_type_html').html();


                } else {

                    $goodsSpecMany.show() && $goodsSpecSingle.hide();
                    $('.goods-spec-single .pay_type_html').html();
                }
            });

            $(document).on('change','.s_pay_type',function (e) {
                if (e.currentTarget.value == 1) {
                    $('.s_goods_price').show();
                    $('.s_goods_integral').hide();
                } else if(e.currentTarget.value == 2) {
                    $('.s_goods_integral').show();
                    $('.s_goods_price').hide();
                }else{
                    $('.s_goods_price').show();
                    $('.s_goods_integral').show();
                }
            })
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});